﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SYH.Common.Utilities
{
    /// <summary>
    /// 缓存扩展类
    /// </summary>
    public static class CacheExtend
    {
        /// <summary>
        /// 缓存扩展方法(注意：使用之前不要使用ToList()方法)
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IList<TSource> ToCache<TSource>(this IEnumerable<TSource> source, string key = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = typeof(TSource).Name;
            }
            var icache = new DataCache();
            var obj = icache.GetList<TSource>(key);
            if (obj == null)
            {
                var list = source.ToList();
                if (list != null && list.Count > 0)
                {
                    icache.Set(key, list);
                }
                return list;
            }
            else
            {
                return obj;
            }
        }

        /// <summary>
        /// 缓存扩展方法(注意：使用之前不要使用ToList()方法)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IList<T> ToCache<T>(this IEnumerable<T> t, int timeout, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = typeof(T).Name;
            }
            var icache = new DataCache();
            var obj = icache.GetList<T>(key);
            if (obj == null)
            {
                var list = t.ToList();
                if (list != null && list.Count > 0)
                {
                    icache.Set(key, list, timeout);
                }

                return list;
            }
            else
            {
                return obj;
            }
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            var icache = new DataCache();
            icache.Remove(key);
        }
    }
}
